package com.hertz.alarm.controller.api;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hertz.alarm.controller.BaseController;
import com.hertz.alarm.controller.support.ResultModel;
import com.hertz.alarm.entity.IrisNbaAlarm;
import com.hertz.alarm.entity.IrisUser;
import com.hertz.alarm.entity.MatchNba;
import com.hertz.alarm.pojo.nba.ResponseIsAlert;
import com.hertz.alarm.service.IrisNbaAlarmService;
import com.hertz.alarm.service.IrisUserService;
import com.hertz.alarm.service.MatchNbaService;
import com.hertz.alarm.service.TeamNbaService;
import com.hertz.alarm.util.Constants;
import com.hertz.alarm.util.Constants4HTTP;
import com.hertz.alarm.util.ConstantsType;
import com.hertz.alarm.util.DateUtils;
import com.hertz.alarm.util.Page;
import com.hertz.alarm.util.ReturnCodeConstants;
import com.hertz.alarm.warper.MatchNbaWarper;
@Controller
@RequestMapping("/api/nbaalarm")
public class ApiNbaAlarmController extends BaseController{

	private Logger logger = LoggerFactory.getLogger(ApiNbaAlarmController.class);
	
	@Resource
	private MatchNbaService matchNbaService;
	@Resource
	private IrisUserService irisUserService;
	@Resource
	private IrisNbaAlarmService irisNbaAlarmService;
	@Resource
	private TeamNbaService teamNbaService;
	
	@RequestMapping(value="sync",method=RequestMethod.POST)
	public @ResponseBody ResultModel<Object> syncData(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="days",required=true)Integer days){
		IrisUser irisUser = (IrisUser)request.getAttribute(Constants4HTTP.REQ_ATTR_USER);
		if(irisUser == null){
			response.setStatus(HttpServletResponse.SC_FORBIDDEN);
			return buildResultModel(null, ReturnCodeConstants.UNEXISTS_USER);
		}
		if(days < 0){
			return buildResultModel(Collections.emptyList());
		}
		List<IrisNbaAlarm> list = new ArrayList<IrisNbaAlarm>();
		for(int i = 0; i < days; i++){
			Calendar c = Calendar.getInstance();
			c.add(Calendar.DATE, i);
			String day = DateUtils.timeFormat(c.getTimeInMillis(), DateUtils.Y_M_D);
			list.addAll(irisNbaAlarmService.listBy(irisUser.getId(), day));
		}
		return buildResultModel(list);
		
	}
	
	@RequestMapping(value="save",method=RequestMethod.POST)
	public @ResponseBody ResultModel<Object> saveNbalAlarm(
			HttpServletRequest request,
			HttpServletResponse response,
			@ModelAttribute IrisNbaAlarm irisNbaAlarm){
		IrisUser irisUser = (IrisUser)request.getAttribute(Constants4HTTP.REQ_ATTR_USER);
//		if(irisUser == null){
//			response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//			return null;
//		}
		if(irisUser == null){
			response.setStatus(HttpServletResponse.SC_FORBIDDEN);
			return buildResultModel(null, ReturnCodeConstants.UNEXISTS_USER);
		}else{
			irisNbaAlarm.setUid(irisUser.getId());
		}
		if(irisNbaAlarm == null){
			return buildResultModel(null);
		}
		if(irisNbaAlarm.getUid() <= 0){
			return buildResultModel(irisNbaAlarm,ReturnCodeConstants.PARAM_ERR_NOUID);
		}
		if(irisNbaAlarm.getMid() <= 0){
			return buildResultModel(irisNbaAlarm,ReturnCodeConstants.PARAM_ERR_NOMID);
		}
		MatchNba matchNba = matchNbaService.getById(irisNbaAlarm.getMid());
		if(matchNba == null){
			return buildResultModel(irisNbaAlarm, ReturnCodeConstants.UNEXISTS_MATCH);
		}
		//can't set alarm,status error
		if( matchNba.getPeriod() != ConstantsType.MATCH_PERIOD.UN_PLAY.getValue()){
			return buildResultModel(irisNbaAlarm, ReturnCodeConstants.STATUS_ERR_MATCHISPLAYING);
		}
		
		if(irisNbaAlarm.getVolume() > Constants.MAX_VOLUME){
			irisNbaAlarm.setVolume(Constants.DEFAULT_VOLUME);
		}
//		//default remain
//		irisNbaAlarm.setRemain(Constants.NBA_ALARM_DEFAULT_REMAIN);
//		//default ring
//		if(StringUtils.isBlank(irisNbaAlarm.getRingName())){
//			irisNbaAlarm.setRingName(Constants.NBA_ALARM_DEFAULT_RING);
//		}
		irisNbaAlarm.setCtime(System.currentTimeMillis());
		irisNbaAlarm.setUtime(System.currentTimeMillis());
		irisNbaAlarmService.save(irisNbaAlarm);
		return buildResultModel(irisNbaAlarm, ReturnCodeConstants.SUCCESS);
	}
	
	@RequestMapping(value="update",method=RequestMethod.POST)
	public @ResponseBody ResultModel<Object> updateNbalAlarm(@ModelAttribute IrisNbaAlarm irisNbaAlarm){
		if(irisNbaAlarm == null){
			return buildResultModel(null);
		}
		if(irisNbaAlarm.getId() == null || irisNbaAlarm.getId() == 0){
			return buildResultModel(null, ReturnCodeConstants.PARAM_ERR_NOALARMID);
		}
		
		IrisNbaAlarm t = irisNbaAlarmService.getById(irisNbaAlarm.getId());
		if(irisNbaAlarm.getUid() <= 0){
			return buildResultModel(irisNbaAlarm,ReturnCodeConstants.PARAM_ERR_NOUID);
		}
		if(irisNbaAlarm.getUid() != t.getUid()){
			return buildResultModel(irisNbaAlarm,ReturnCodeConstants.NOPERMISSION_ALARM);
		}
		
		MatchNba matchNba = matchNbaService.getById(irisNbaAlarm.getMid());
		if(matchNba == null){
			return buildResultModel(irisNbaAlarm, ReturnCodeConstants.UNEXISTS_MATCH);
		}
		//can't set alarm,status error
		if( matchNba.getPeriod() != ConstantsType.MATCH_PERIOD.UN_PLAY.getValue()){
			return buildResultModel(irisNbaAlarm, ReturnCodeConstants.STATUS_ERR_MATCHISPLAYING);
		}
		
		//default volumn
		if(irisNbaAlarm.getVolume() > Constants.MAX_VOLUME){
			irisNbaAlarm.setVolume(Constants.DEFAULT_VOLUME);
		}
		//default remain
		irisNbaAlarm.setRemain(Constants.NBA_ALARM_DEFAULT_REMAIN);
		//default ring
		if(StringUtils.isBlank(irisNbaAlarm.getRingName())){
			irisNbaAlarm.setRingName(Constants.NBA_ALARM_DEFAULT_RING);
		}
		irisNbaAlarm.setUtime(System.currentTimeMillis());
		irisNbaAlarmService.update(t,irisNbaAlarm);
		return buildResultModel(irisNbaAlarm);
	}
	
	@RequestMapping(value="getsByYMD",method=RequestMethod.GET)
	public @ResponseBody ResultModel<Object> getByYmd(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="ymd",required=false) String ymd){
		IrisUser irisUser = (IrisUser)request.getAttribute(Constants4HTTP.REQ_ATTR_USER);
//		if(irisUser == null){
//			response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//			return null;
//		}
		if(irisUser == null){
			response.setStatus(HttpServletResponse.SC_FORBIDDEN);
			return buildResultModel(null, ReturnCodeConstants.UNEXISTS_USER);
		}
		if(StringUtils.isBlank(ymd)){
			ymd = DateUtils.timeFormat(System.currentTimeMillis() , DateUtils.Y_M_D);
		}
		List<IrisNbaAlarm> list = irisNbaAlarmService.listBy(irisUser.getId(), ymd);
		Page<IrisNbaAlarm> page = new Page<IrisNbaAlarm>();
		page.setResult(list);
		page.setTotalCount(list.size());
		return buildResultModel(page);
	}
	
	@RequestMapping(value="get",method=RequestMethod.POST)
	public @ResponseBody ResultModel<Object> get(
			@RequestParam(value="token",required=true) String token,
			@RequestParam(value="id",required=true) long id){
		IrisUser irisUser = irisUserService.getByToken(token);
		if(irisUser == null){
			return buildResultModel(null, ReturnCodeConstants.UNEXISTS_USER);
		}
		if(id == 0){
			return buildResultModel(null,ReturnCodeConstants.PARAM_ERR_NOALARMID);
		}
		IrisNbaAlarm irisNbaAlarm = irisNbaAlarmService.getById(id);
		if(irisNbaAlarm == null){
			return buildResultModel(null,ReturnCodeConstants.UNEXISTS_ALARM);
		}
		return buildResultModel(irisNbaAlarm);
	}
//	
//	@RequestMapping(value="isAlarm",method=RequestMethod.POST)
//	public @ResponseBody ResultModel<Object> isAlarm(
//			@RequestParam(value="token",required=true) String token){
//		IrisUser irisUser = irisUserService.getBytoken(token);
//		if(irisUser == null){
//			return buildResultModel(null, ReturnCodeConstants.UNEXISTS_USER);
//		}
//		
//		List<MatchNba> list = irisNbaAlarmService.isAlarm(irisUser);
//		if(list == null || list.isEmpty()){
//			return buildResultModel(list,ReturnCodeConstants.NOT_ALARM);
//		}else{
//			return buildResultModel(list);
//		}
//	}
	
	/**
	 * 
	 * @param token
	 * @param auids split by ,
	 * @return
	 */
	@RequestMapping(value="isAlert",method=RequestMethod.POST)
	public @ResponseBody ResultModel<Object> isAlarm(
			@RequestParam(value="mid",required=true) Long mid,
			HttpServletRequest request,
			HttpServletResponse response){
		IrisUser irisUser = (IrisUser)request.getAttribute(Constants4HTTP.REQ_ATTR_USER);
		if(irisUser == null){
			response.setStatus(HttpServletResponse.SC_FORBIDDEN);
			return buildResultModel(null, ReturnCodeConstants.UNEXISTS_USER);
		}
		if(mid == null || mid == 0){
			return buildResultModel(null,ReturnCodeConstants.UNEXISTS_MATCH);
		}
		MatchNba matchNba = matchNbaService.getById(mid);
		if(matchNba == null){
			return buildResultModel(null,ReturnCodeConstants.UNEXISTS_MATCH);
		}
		IrisNbaAlarm irisNbaAlarm = irisNbaAlarmService.getBy(irisUser.getId(), mid);
		if(irisNbaAlarm == null){
			return buildResultModel(null, ReturnCodeConstants.UNEXISTS_ALARM);
		}
		boolean isAlarm = irisNbaAlarmService.isALarm(matchNba, irisNbaAlarm);
		ResponseIsAlert ria = new ResponseIsAlert();
		ria.setAlert(isAlarm);
		if(irisNbaAlarm.getStatus() != ConstantsType.ALARM_STATUS.end_alarm.getValue()){
			ria.setAfter(Constants.INTERVAL_MS);
		}else{
			ria.setAfter(-1);
		}
		ria.setGuestTeam(teamNbaService.getTeamBySourceId(String.valueOf(matchNba.getGuestTeamId())));
		ria.setHostTeam(teamNbaService.getTeamBySourceId(String.valueOf(matchNba.getHostTeamId())));
		
		ria.setMatchNba(matchNba);
		ria.setIrisNbaAlarm(irisNbaAlarm);
//		List<IrisNbaAlarm> list = irisNbaAlarmService.listBy(irisUser.getId(), DateUtils.today(DateUtils.Y_M_D));
//		if(list == null || list.isEmpty()){
//			return buildResultModel(null,ReturnCodeConstants.UNEXISTS_ALARM);
//		}
//		List<ResponseIsAlert> result = new ArrayList<ResponseIsAlert>();
//		for(int i = 0; i < list.size(); i++){
//			IrisNbaAlarm item = list.get(i);
//			
//			MatchNba match = irisNbaAlarmService.isAlarm(irisUser, item);
//			ResponseIsAlert ria = new ResponseIsAlert();
//			if(match != null){
//				ria.setIrisNbaAlarm(item);
//				ria.setStatus(ConstantsType.ALARM_STATUS.do_alarm.getValue());
//				ria.setMatchNba(match);
//				ria.setGuestTeam(match == null ? null : teamNbaService.getTeamBySourceId(String.valueOf(match.getGuestTeamId())));
//				ria.setHostTeam(match == null ? null : teamNbaService.getTeamBySourceId(String.valueOf(match.getHostTeamId())));
//			}else{
//				ria.setIrisNbaAlarm(item);
//				ria.setAfter(Constants.INTERVAL_MS);
//				ria.setStatus(ConstantsType.ALARM_STATUS.un_alarm.getValue());
//				ria.setMatchNba(matchNbaService.getById(item.getMid()));
//				ria.setGuestTeam(teamNbaService.getTeamBySourceId(String.valueOf(ria.getMatchNba().getGuestTeamId())));
//				ria.setHostTeam(teamNbaService.getTeamBySourceId(String.valueOf(ria.getMatchNba().getHostTeamId())));
//			}
//			result.add(ria);
//		}
		return buildResultModel(ria);
	}

	
	@RequestMapping(value="cancel",method=RequestMethod.POST)
	public @ResponseBody ResultModel<Object> cancel(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="mid",required=true) long mid
			){
		IrisUser irisUser = (IrisUser)request.getAttribute(Constants4HTTP.REQ_ATTR_USER);
		if(irisUser == null){
			response.setStatus(HttpServletResponse.SC_FORBIDDEN);
			return buildResultModel(null, ReturnCodeConstants.UNEXISTS_USER);
		}
		IrisNbaAlarm irisNbaAlarm = irisNbaAlarmService.getBy(irisUser.getId(), mid);
		
		if(irisNbaAlarm == null){
			logger.error("no alarm,user.id={},mid={}",irisUser.getId(),mid);
			return buildResultModel(null,ReturnCodeConstants.UNEXISTS_ALARM);
		}
		
//		irisNbaAlarm.setStatus(ConstantsType.ALARM_STATUS.user_cancel.getValue());
//		irisNbaAlarm.setUtime(System.currentTimeMillis());
		irisNbaAlarmService.cancel(irisNbaAlarm.getId());
		return buildResultModel(null,ReturnCodeConstants.SUCCESS);
	}
}
